<template>
  <a-row :gutter="10">
    <a-col :md="12" :sm="24">
      <a-card :bordered="false">

        <!-- 按钮操作区域 -->
        <a-row style="margin-left: 14px">
          <a-button :disabled='userDisable' @click="bindUser" type="primary">用户管理</a-button>
<!--          <a-button title="删除多条数据" @click="batchDel" type="default">批量删除</a-button>-->
          <span>
            人员
          </span>
          <a-switch checked-children="显示" un-checked-children="隐藏" default-checked @change="showUser"/>
        </a-row>
        <div style="background: #fff;padding-left:16px;height: 100%; margin-top: 5px">
          <a-alert type="info" :showIcon="true">
            <div slot="message">
              当前选择：
              <a v-if="this.currSelected.title">{{ getCurrSelectedTitle() }}</a>
              <a v-if="this.currSelected.title" style="margin-left: 10px" @click="onClearSelected">取消选择</a>
            </div>
          </a-alert>
          <!-- 树-->
          <a-col :md="10" :sm="24">
            <template>
              <a-dropdown :trigger="[this.dropTrigger]" @visibleChange="dropStatus">
               <span style="user-select: none">
            <a-tree
              checkable
              id="tree"
              multiple
              @select="onSelect"
              @load="getNode"
              :load-data="onLoadData"
              :loadedKeys="loadedKeys"
              @check="onCheck"
              :show-icon="true"
              @rightClick="rightHandle"
              :selectedKeys="selectedKeys"
              :checkedKeys="checkedKeys"
              :treeData="treeData"
              :expandedKeys="iExpandedKeys"
              :autoExpandParent="autoExpandParent"
              @expand="onExpand">
               <a-icon slot="home" type="home" />
               <a-icon slot="apartment" type="apartment" />
               <a-icon slot="user" type="user" />
               </a-tree>
                </span>
                <!--新增右键点击事件,和增加添加和删除功能-->
                <a-menu slot="overlay">
                  <a-menu-item v-show="isArea===1" @click="handleAdd(3)" key="5">添加项目</a-menu-item>
                  <a-menu-item v-show="isArea===1" @click="handleAdd(1)" key="1" >添加区域</a-menu-item>
                  <a-menu-item v-show="isArea===1" key="2" >
                    <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete()">
                    <a>删除</a>
                  </a-popconfirm>
                  </a-menu-item>
                  <a-menu-item v-show="isArea===1||isArea==0" @click="deleteBind" key="3">解绑</a-menu-item>
                  <a-menu-item v-show="isArea===1||isArea==0" @click="closeDrop" key="4">取消</a-menu-item>
                </a-menu>
              </a-dropdown>
            </template>
          </a-col>
        </div>
      </a-card>
    </a-col>
    <area-modal ref="areaModal" @ok="refresh"></area-modal>
    <select-project ref="selectProject" @ok="refresh"></select-project>
    <bind-user-form ref="bindUserForm" @ok="resetShow"></bind-user-form>
  </a-row>
</template>
<script>
import AreaModal from './modules/AreaModal'
import SelectProject from './modules/SelectProject'
import pick from 'lodash.pick'
import {querySysAreaTreeList} from '@/api/api'
import {deleteAction, httpAction , getAction} from '@/api/manage'
import {JeecgListMixin} from '@/mixins/JeecgListMixin'
import bindUserForm from "@views/passage/AreaTreeModules/BindUserForm";

// 表头
const columns = [
  {
    title: '机构名称',
    dataIndex: 'departName'
  },
  {
    title: '机构类型',
    align: 'center',
    dataIndex: 'orgType'
  },
  {
    title: '机构编码',
    dataIndex: 'orgCode',
  },
  {
    title: '手机号',
    dataIndex: 'mobile'
  },
  {
    title: '传真',
    dataIndex: 'fax'
  },
  {
    title: '地址',
    dataIndex: 'address'
  },
  {
    title: '排序',
    align: 'center',
    dataIndex: 'departOrder'
  },
  {
    title: '操作',
    align: 'center',
    dataIndex: 'action',
    scopedSlots: {customRender: 'action'}
  }
]
export default {
  name: 'DepartList',
  mixins: [JeecgListMixin],
  components: {
    SelectProject,
    AreaModal,
    bindUserForm,

  },
  data() {
    return {
      loadedKeys: [],
      userDisable:true,
      iExpandedKeys: [],
      loading: false,
      autoExpandParent: true,
      currFlowId: '',
      currFlowName: '',
      disable: true,
      treeData: [],
      visible: false,
      rightClickSelectedKey: '',
      hiding: true,
      model: {},
      dropTrigger: '',
      depart: {},
      columns: columns,
      disableSubmit: false,
      checkedKeys: [],
      selectedKeys: [],
      autoIncr: 1,
      currSelected: {},
      form: this.$form.createForm(this),
      labelCol: {
        xs: {span: 24},
        sm: {span: 5}
      },
      wrapperCol: {
        xs: {span: 24},
        sm: {span: 16}
      },
      graphDatasource: {
        nodes: [],
        edges: []
      },
      validatorRules: {
        name: {rules: [{required: true, message: '请输入区域名称!'}]},

      },
      url: {
        delete: '/sysArea/delete',
        edit: '/area/updateById',
        deleteBatch: '/area/deleteBatch',
        projectRemoveBind:"/project/removeBind",
        projectGetUser:"/project/getSysUser",
        areaRemoveBind:"/sysArea/removeBind",
        userRemoveBind:"/sys/user/removeBind",
        getChildren:"/sysArea/getChildren"
      },
      isArea: 0,
      userShow:true,
      rightSelectNode:{}
    }
  },
  computed: {
    importExcelUrl: function () {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`;
    }
  },
  methods: {
    getNode(loadedKeys){
        this.loadedKeys = loadedKeys
    },
    onLoadData(treeNode) {
        return new Promise((resolve) => {
          setTimeout(() => {
            let url =""
            if (treeNode.dataRef.isArea==1){
               url = this.url.getChildren
            }else if(treeNode.dataRef.isArea ==0){
              url = this.url.projectGetUser
            }
            if(url!=""){
              getAction(url,{id:treeNode.dataRef.key}).then((res)=>{
                if (res.success&&res.result!=null){
                  treeNode.dataRef.children = res.result
                }
              })
            }
            this.treeData = [...this.treeData];
            resolve();
          }, 100);
        });
      },
    loadData() {
      this.refresh();
    },
    findAllChildNodeKeys(node, data, keys) {
      if (node !== undefined && node !== null && node.children !== null) {
        for (let index = 0; index < data.length; index++) {
          let itemNode = data[index]
          this.findAllChildNodeKeys(itemNode, itemNode.children, keys)
          keys.push(itemNode.key)
        }
      }
    },
    findNode(key, data) {
      let node = null
      if (data !== undefined && data !== null) {
        for (let index = 0; index < data.length; index++) {
          let res = data[index]
          if (res.key === key) {
            return res
          }
          node = this.findNode(key, res.children)

          if (node !== null && node !== undefined) {
            return node
          }
        }
      } else {
        return null
      }
    },
    resetShow(){
      this.loadedKeys=[]
      if (this.userShow===false){
        this.deleteUser(this.treeData)
      }else {
        this.loadTree()
      }
    },
    loadTree() {
      let that = this
      this.loadedKeys = []
      that.treeData = []
      querySysAreaTreeList().then((res) => {
        if (res.success) {
          for (let i = 0; i < res.result.length; i++) {
            let temp = res.result[i]
            that.treeData.push(temp)
            // that.setThisExpandedKeys(temp)
          }
          this.loading = false
        }
      })
      console.log(that.treeData)
    },
    setThisExpandedKeys(node) {
      if (node.children && node.children.length > 0) {
        this.iExpandedKeys.push(node.key)
        for (let a = 0; a < node.children.length; a++) {
          this.setThisExpandedKeys(node.children[a])
        }
      }
    },
    refresh() {
      
      this.loading = true
      this.loadTree()
    },
    // 右键操作方法
    rightHandle(node) {
      this.dropTrigger = 'contextmenu'
      this.isArea = node.node.dataRef.isArea
      this.rightClickSelectedKey = node.node.eventKey
      this.rightSelectNode = node.node.dataRef
    },
    onExpand(expandedKeys) {
      // if not set autoExpandParent to false, if children expanded, parent can not collapse.
      // or, you can remove all expanded children keys.
      this.iExpandedKeys = expandedKeys
      this.autoExpandParent = false
    },
    backFlowList() {
      this.$router.back(-1)
    },
    // 右键点击下拉框改变事件
    dropStatus(visible) {
      if (visible == false) {
        this.dropTrigger = ''
      }
    },
    // 右键店家下拉关闭下拉框
    closeDrop() {
      this.dropTrigger = ''
    },
    addRootNode() {
      this.$refs.nodeModal.add(this.currFlowId, '')
    },
    batchDel: function () {
      if (this.checkedKeys.length <= 0) {
        this.$message.warning('请选择一条记录！')
      } else {
        var ids = ''
        for (var a = 0; a < this.checkedKeys.length; a++) {
          ids += this.checkedKeys[a] + ','
        }
        var that = this
        this.$confirm({
          title: '确认删除',
          content: '确定要删除所选中的 ' + this.checkedKeys.length + ' 条数据?',
          onOk: function () {
            deleteAction(that.url.deleteBatch, {ids: ids}).then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.loadTree()
                that.onClearSelected()
              } else {
                that.$message.warning(res.message)
              }
            })
          }
        })
      }
    },
    nodeModalOk() {
      this.loadTree()
    },
    nodeModalClose() {
    },
    hide() {
      this.visible = false
    },
    onCheck(checkedKeys, info) {
      this.checkedKeys = checkedKeys
      let iExpandedKeys = Object.assign([], checkedKeys)
      this.pushAllParentKey(iExpandedKeys)
      this.iExpandedKeys = iExpandedKeys
      this.selectedKeys = []

      this.autoExpandParent = false
    },
    pushAllParentKey(keys) {
      let count = 0
      keys.forEach(res => {
        count++
        let node = this.findNode(res, this.treeData)
        this.pushParentKey(node, keys)
      })
    },
    pushParentKey(node, keys) {
      if (node.parentId !== null && !keys.includes(node.parentId)) {
        keys.push(node.parentId)
        this.pushParentKey(this.findNode(node.parentId, this.treeData), keys)
      }
    },
    findAllParentNodeKeys(node, parentKeys) {
      if (node.parentId !== null) {
        parentKeys.push(node.parentId)
        this.findAllParentNodeKeys(this.findNode(node.parentId, this.treeData), parentKeys)
      }
    },
    getChild(keys) {
      keys.forEach(res => {

      })
    },
    onSelect(selectedKeys, e) {
      this.hiding = false
      let record = e.node.dataRef
      this.isArea = record.isArea
      if (record.isArea!=2){
        this.userDisable = false
      }else {
        this.userDisable = true
      }
      this.currSelected = Object.assign({}, record)
      this.model = this.currSelected
      this.selectedKeys = [record.key]
      this.model.parentId = record.parentId
      this.setValuesToForm(record)
      this.checkedKeys = []


    },
    // 触发onSelect事件时,为区域树右侧的form表单赋值
    setValuesToForm(record) {
      this.form.getFieldDecorator('fax', {initialValue: ''})
      this.form.setFieldsValue(pick(record, 'name', 'sort', 'status', 'areaCode', 'remark'))
    },
    getCurrSelectedTitle() {
      return !this.currSelected.title ? '' : this.currSelected.title
    },
    onClearSelected() {
      this.hiding = true
      this.checkedKeys = []
      this.currSelected = {}
      this.form.resetFields()
      this.selectedKeys = []
    },
    handleNodeTypeChange(val) {
      this.currSelected.nodeType = val
    },
    notifyTriggerTypeChange(value) {
      this.currSelected.notifyTriggerType = value
    },
    receiptTriggerTypeChange(value) {
      this.currSelected.receiptTriggerType = value
    },
    submitCurrForm() {
      this.form.validateFields((err, values) => {
        if (!err) {
          if (!this.currSelected.id) {
            this.$message.warning('请点击选择要修改区域!')
            return
          }

          let formData = Object.assign(this.currSelected, values)
          httpAction(this.url.edit, formData, 'post').then((res) => {
            if (res.success) {
              this.$message.success('保存成功!')
              this.loadTree()
            } else {
              this.$message.error(res.message)
            }
          })
        }
      })
    },
    emptyCurrForm() {
      this.form.resetFields()
    },
    openSelect() {
      this.$refs.sysDirectiveModal.show()
    },
    bindUser() {
      let key = []
      if (!(this.checkedKeys === undefined || this.checkedKeys === null || this.checkedKeys.length === 0)) {
        this.checkedKeys.forEach(res => {
          let node = this.findNode(res, this.treeData)
          if (this.checkParentNode(node, key) === true) {
              if (node.isArea === 0) {
                // 如果节点是项目，则检查key中是否有父节点
                if (!key.includes(node.parentId)) {
                  // 如果没有父节点，则添加该项目
                  key.push(node)
                }
              } else {
                let newNode  = Object.assign({},node)
                // 如果节点是区域，则检测key中是否有子节点
                if (newNode.children !== null) {
                  // 如果存在，则去除子节点
                  key = key.filter(res => {
                    return !newNode.children.includes(res)
                  })
                  newNode.children = newNode.children.filter(res=>{
                    return res.isArea!==3
                  })
                }
                // 添加节点
                key.push(newNode)
              }

          }
        })
        this.deleteUser(key)
        this.$refs.bindUserForm.show(key)
        return;
      } else if (this.selectedKeys !== undefined && this.selectedKeys !== null && this.selectedKeys.length !== 0) {
        let node = this.findNode(this.selectedKeys[0], this.treeData)
        key.push(node)
        this.deleteUser(key)
        /*清除人员*/
        this.$refs.bindUserForm.show(key)
        return
      }
      this.$message.warn("请至少选择一个部门")
    },
    checkParentNode(Node, keys) {
      if(Node.isArea===3)
      {
        return false
      }
      if (Node.parentId !== null) {
        let parent = this.findNode(Node.parentId, this.treeData)
        for(let index = 0;index<keys.length;index++)
        {
          let item = keys[index]
          if(item.key === parent.key)
          {
            return false
          }
        }
        if (this.checkParentNode(parent, keys)) {
            return true
        }
      } else {
        return true
      }

    },
    bindAdmin() {
      if (this.checkedKeys === undefined || this.checkedKeys === null || this.checkedKeys.length === 0) {
        this.$message.warn("请至少选择一个部门")
        return;
      }
      let key = []
      this.checkedKeys.forEach(res => {
        let node = this.findNode(res, this.treeData)
        if (node.isArea === 1) {
          if (node.children !== null && node.children[0].isArea === 0) {
            key.push(node)
          } else if (node.children === null) {
            key.push(node)
          }
        }
      })
      this.$refs.bindUserForm.show(key)
    },
    handleDelete(){
     deleteAction(this.url.delete,{id:this.rightClickSelectedKey}).then((res)=>{
       if (res.success){
         this.$message.success("删除成功")
          
         this.loadTree()
       }else {
         this.$message.warn(res.message)
       }
     })
    },
    handleAdd(num) {
      if (num === 1) {

        this.$refs.areaModal.add(this.rightClickSelectedKey)
        this.$refs.areaModal.title = '新增'
      } else {
        this.$refs.selectProject.setAreaId(this.rightClickSelectedKey)
        this.$refs.selectProject.title = '添加项目'
      }
    },
    deleteBind() {
      let that = this
      let url
      /*右键解绑*/
      if(this.rightSelectNode.isArea === 0)
      {
        /*项目的解绑*/
        url = this.url.projectRemoveBind
      }
      if(this.rightSelectNode.isArea === 1)
      {
        /*区域的解绑*/
        url = this.url.areaRemoveBind
      }
      deleteAction(url, {id: that.rightSelectNode.value}).then((res) => {
        if (res.success) {
          that.$message.success(res.message)
          this.loadedKeys=[]
          that.loadTree()
          that.onClearSelected()
        } else {
          that.$message.warning(res.message)
        }
      })
    },
    selectDirectiveOk(record) {
      this.nodeSettingForm.setFieldsValue({directiveCode: record.directiveCode})
      this.currSelected.sysCode = record.sysCode
    },
    getFlowGraphData(node) {
      this.graphDatasource.nodes.push({
        id: node.id,
        text: node.flowNodeName
      })
      if (node.children.length > 0) {
        for (let a = 0; a < node.children.length; a++) {
          let temp = node.children[a]
          this.graphDatasource.edges.push({
            source: node.id,
            target: temp.id
          })
          this.getFlowGraphData(temp)
        }
      }
    },
    showUser(checked){
      this.userShow = checked
      if (this.userShow===false){
        this.deleteUser(this.treeData)
      }else {
        this.loadTree()
      }
      // let node = document.getElementById("tree").__vue__
      //
      // this.loopTreeData(node.$children)
    },
    /*遍历树，删除为人员的节点*/
    deleteUser(treeData){
      if (treeData.length>0&&treeData!=null){
        for (let i = 0; i < treeData.length; i++) {
          if (treeData[i].isArea===2){
            console.log(treeData[i].title)
            treeData.splice(i,1)
            this.deleteUser(treeData)
            continue
          }
          if (treeData[i].children!=null&&treeData[i].children.length>0){
            this.deleteUser(treeData[i].children)
          }


        }
      }
    },

    loopTreeData(data){
      data.forEach(res=>{
        if(Array.isArray(res.$children))
        {
          this.loopTreeData(res.$children)
        }

        let data = res._props.dataRef
        if(data!==undefined&&data.isArea ===2)
        {
          if(!this.userShow)
          {
            res.$el.style = 'display : none'
          }else {
            res.$el.style = ''
          }
        }
      })
    }
  },
  created() {
    this.currFlowId = this.$route.params.id
    this.currFlowName = this.$route.params.name
    // this.loadTree()
  },


}
</script>
<style scoped>
.ant-card-body .table-operator {
  margin: 15px;
}

.anty-form-btn {
  width: 100%;
  text-align: center;
}

.anty-form-btn button {
  margin: 0 5px;
}

.anty-node-layout .ant-layout-header {
  padding-right: 0
}

.header {
  padding: 0 8px;
}

.header button {
  margin: 0 3px
}

.ant-modal-cust-warp {
  height: 100%
}

.ant-modal-cust-warp .ant-modal-body {
  height: calc(100% - 110px) !important;
  overflow-y: auto
}

.ant-modal-cust-warp .ant-modal-content {
  height: 90% !important;
  overflow-y: hidden
}

#app .desktop {
  height: auto !important;
}

/** Button按钮间距 */
.ant-btn {
  margin-left: 3px
}
.userNodeUnShow{
  display: none !important;;
}
.userNodeShow{

}
</style>